package com.slf.common;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.*;

public class LoggerUtil {

	private static Map<String,Logger> map = new ConcurrentHashMap<String,Logger>();
	
	public static synchronized Logger getLogger(String logName){
		Logger logger = map.get(logName);
		if(logger==null){
			logger = Logger.getLogger(logName);
			String logAddr;
			try {
				logAddr = getLogName(logName);
				setLogingProperties(logAddr,logger, Level.ALL);
			} catch (IOException e) {
				e.printStackTrace();
			}
			map.put(logName, logger);
		}
		return logger;
	}

	


	public static void setLogingProperties(String logAddr,Logger logger, Level level) {

		FileHandler fh;
		try {
			
			fh = new FileHandler(logAddr, true);

			logger.addHandler(fh);// ��־����ļ�

			// logger.setLevel(level);

			fh.setFormatter(new MyFormatter());// �����ʽ

			// logger.addHandler(new ConsoleHandler());//���������̨

		} catch (SecurityException e) {

			logger.log(Level.SEVERE, "SecurityException:", e);

		} catch (IOException e) {

			logger.log(Level.SEVERE, "IOException:", e);

		}
	}
	
	/**
	 * 
	 * �õ�Ҫ��¼����־��·�����ļ�����
	 * 
	 * @return
	 * @throws IOException 
	 */
	private static String getLogName(String logName) throws IOException {
		Calendar calendar = Calendar.getInstance();
		String logPath = "log";
		
		File file = new File(logPath);
		if (!file.exists()){
			file.mkdir();
		}
		
		file = new File(logPath);
		if (!file.exists()){
			file.mkdir();
		}
		
		logPath = logPath + "/" + logName +".log";
		
		file = new File(logPath);

		if (!file.exists()) {
            file.createNewFile();
        }

		return logPath;
	}
}
class MyFormatter extends Formatter {
	 
    @Override
    public String format(LogRecord arg0) {
        // TODO Auto-generated method stub
        //����StringBuilder��������ź�����Ҫ��ӡ����־����
        StringBuilder builder = new StringBuilder();
         
        //��ȡʱ��
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
        Date now = new Date();
        String dateStr = sdf.format(now);
         
        builder.append(dateStr);
        builder.append(" - ");
         
        //ƴ����־����
        builder.append(arg0.getLevel()).append(" - ");
         
        //ƴ�ӷ�����
        builder.append(arg0.getSourceMethodName()).append(" - ");
         
        //ƴ����־����
        builder.append(arg0.getMessage());
        //��־����
        builder.append("\r\n");
         
        return builder.toString();
    }
     
    @Override
    public String getHead(Handler h) {
        // TODO Auto-generated method stub
        return "";
    }
     
    @Override
    public String getTail(Handler h) {
        // TODO Auto-generated method stub
        return "";
    }
 
}


